using Microsoft.AspNetCore.Mvc;
using ERPBackend.Models;
using ERPBackend.Services;
using System.Threading.Tasks;
using System;

namespace ERPBackend.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class PurchaseReceiptsController : ControllerBase
    {
        private readonly IPurchaseReceiptService _purchaseReceiptService;

        public PurchaseReceiptsController(IPurchaseReceiptService purchaseReceiptService)
        {
            _purchaseReceiptService = purchaseReceiptService;
        }

        // GET: api/PurchaseReceipts
        [HttpGet]
        public async Task<ActionResult<object>> GetPurchaseReceipts(int page = 1, int pageSize = 10)
        {
            var total = await _purchaseReceiptService.GetTotalPurchaseReceiptsAsync();
            var receipts = await _purchaseReceiptService.GetPurchaseReceiptsPagedAsync(page, pageSize);
            return Ok(new { items = receipts, total });
        }

        // GET: api/PurchaseReceipts/5
        [HttpGet("{id}")]
        public async Task<ActionResult<PurchaseReceipt>> GetPurchaseReceipt(int id)
        {
            var receipt = await _purchaseReceiptService.GetPurchaseReceiptByIdAsync(id);

            if (receipt == null)
            {
                return NotFound();
            }

            return receipt;
        }

        // GET: api/PurchaseReceipts/code/{receiptCode}
        [HttpGet("code/{receiptCode}")]
        public async Task<ActionResult<PurchaseReceipt>> GetPurchaseReceiptByCode(string receiptCode)
        {
            var receipt = await _purchaseReceiptService.GetPurchaseReceiptByCodeAsync(receiptCode);

            if (receipt == null)
            {
                return NotFound();
            }

            return receipt;
        }

        // PUT: api/PurchaseReceipts/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutPurchaseReceipt(int id, PurchaseReceipt receipt)
        {
            if (id != receipt.Id)
            {
                return BadRequest();
            }

            try
            {
                var updated = await _purchaseReceiptService.UpdatePurchaseReceiptAsync(receipt);
                if (!updated)
                {
                    return NotFound();
                }
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }

            return NoContent();
        }

        // POST: api/PurchaseReceipts
        [HttpPost]
        public async Task<ActionResult<PurchaseReceipt>> PostPurchaseReceipt(PurchaseReceipt receipt)
        {
            try
            {
                var createdReceipt = await _purchaseReceiptService.CreatePurchaseReceiptAsync(receipt);
                return CreatedAtAction("GetPurchaseReceipt", new { id = createdReceipt.Id }, createdReceipt);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
        }

        // DELETE: api/PurchaseReceipts/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeletePurchaseReceipt(int id)
        {
            var deleted = await _purchaseReceiptService.DeletePurchaseReceiptAsync(id);
            if (!deleted)
            {
                return NotFound();
            }

            return NoContent();
        }

        // PATCH: api/PurchaseReceipts/5/status
        [HttpPatch("{id}/status")]
        public async Task<IActionResult> ChangePurchaseReceiptStatus(int id, [FromBody] byte status)
        {
            var success = await _purchaseReceiptService.ChangePurchaseReceiptStatusAsync(id, status);
            if (!success)
            {
                return NotFound();
            }

            return NoContent();
        }

        // PATCH: api/PurchaseReceipts/5/approve
        [HttpPatch("{id}/approve")]
        public async Task<IActionResult> ApprovePurchaseReceipt(int id, [FromBody] PurchaseApproveRequest request)
        {
            try
            {
                if (!int.TryParse(request.ApprovedBy, out int approverId))
                {
                    return BadRequest("审批人ID必须是有效的整数");
                }
                var success = await _purchaseReceiptService.ApprovePurchaseReceiptAsync(id, approverId, request.ApprovalRemark);
                if (!success)
                {
                    return NotFound();
                }
                return NoContent();
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }

    // 采购收货审核请求模型
    public class PurchaseApproveRequest
    {
        public string ApprovalRemark { get; set; }
        public string ApprovedBy { get; set; }
    }
}